package com.gitee.candy.string;

import javax.servlet.http.HttpServletRequest;


public class IpUtil {
    /**
     * 获取客户端ip
     *
     * @param request HttpServletRequest对象
     * @return 客户端ip
     */
    public static String getCustomerIP(HttpServletRequest request) {

        // 由于公司内部服务器都由F5、Nginx反向代理，因此优先从X-Forwarded-For转发头中获取
        String forwardedIP = request.getHeader("X-Forwarded-For");   //格式X-Forwarded-For: client1, proxy1, proxy2
        if (forwardedIP != null && forwardedIP.length() != 0 & !"unKnown".equalsIgnoreCase(forwardedIP)) {
            if (!forwardedIP.contains(",")) {
                // 只有一个时直接返回
//            	logger.debug("--->this is forwardedIP: "+forwardedIP);
                return forwardedIP;
            }
            for (String ip : forwardedIP.split(",")) {
                // 获取第一个非unknown的ip
                if (ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
//                	logger.debug("--->this is ip: "+ip);
                    return ip;
                }
            }
        }
        // X-Forwarded-For头中无法获取，尝试从X-Real-IP头中获取
        String realIP = request.getHeader("X-Real-IP");
        if (realIP == null || realIP.length() == 0 || "unknown".equalsIgnoreCase(realIP)) {
//        	logger.debug("--->this is realIP: "+realIP);
            return realIP;
        }
        String remoteAddr = request.getRemoteAddr();
        if ("0:0:0:0:0:0:0:1".equals(remoteAddr)) {
            //排除ipv6本地地址（本机调用时，可能产生0:0:0:0:0:0:0:1这样的ipv6地址）
            remoteAddr = "127.0.0.1";
        }
//        logger.debug("--->this is remoteAddr: "+remoteAddr);
        return remoteAddr;
    }

    // 将127.0.0.1形式的IP地址转换成十进制整数，这里没有进行任何错误处理
    public static long ipToLong(String strIp) {
        long[] ip = new long[4];
        // 先找到IP地址字符串中.的位置
        int position1 = strIp.indexOf(".");
        int position2 = strIp.indexOf(".", position1 + 1);
        int position3 = strIp.indexOf(".", position2 + 1);
        // 将每个.之间的字符串转换成整型
        ip[0] = Long.parseLong(strIp.substring(0, position1));
        ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
        ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
        ip[3] = Long.parseLong(strIp.substring(position3 + 1));
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
    }

    // 将十进制整数形式转换成127.0.0.1形式的ip地址
    public static String longToIP(long longIp) {
        // 直接右移24位
        // 将高8位置0，然后右移16位
        // 将高16位置0，然后右移8位
        // 将高24位置0
        return String.valueOf((longIp >>> 24)) +
                "." +
                String.valueOf((longIp & 0x00FFFFFF) >>> 16) +
                "." +
                String.valueOf((longIp & 0x0000FFFF) >>> 8) +
                "." +
                String.valueOf((longIp & 0x000000FF));
    }

}
